<template>
  <div>
    <el-form label-position="right" size="small" label-width="110px" class="base-search-more">
      <el-row >
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="所属区域">
            <el-select style="width:100%" v-model="form.agentid" filterable default-first-option
                       placeholder="--区域-" @change="inquiry()">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="骑手名字">
            <el-input v-model="params.name" style="width: 100%;" placeholder="请选择" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工作性质">
            <el-select v-model="params.workType" style="width: 100%;" placeholder="请选择" clearable>
              <el-option label="全职" :value="1" />
              <el-option label="兼职" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="启用状态">
            <el-select v-model="params.status" style="width: 100%;" placeholder="请选择" clearable>
              <el-option label="启用中" :value="0" />
              <el-option label="已停用" :value="-1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent?24:6" style="text-align:right;">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="$refs.pagination.handleSizeChange(10)">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="base-table-wrap">
      <el-row type="flex" justify="space-bteween" align="middle" style="height: 50px;">
        <el-col :span="18" type="flex">
          <span class="trim">工作状态：</span>
          <span class="btns" :class="{'cur':params.type=='0'}" @click="selectSearch('0')">全部:
            <span>{{tableData.count||'0'}}</span>人
          </span>
          <span class="btns" :class="{'cur':params.type=='1'}" @click="selectSearch('1')">工作中:
            <span>{{tableData.work1||'0'}}</span>人
          </span>
          <span class="btns" :class="{'cur':params.type=='2'}" @click="selectSearch('2')">下班中：
            <span>{{tableData.work0||'0'}}</span>人
          </span>
          <span class="trim">其它：</span>
          <span class="btns" :class="{'cur':params.type=='3'}" @click="selectSearch('3')">停用：
            <span>{{tableData.status1||'0'}}</span>人
          </span>
          <span class="btns" :class="{'cur':params.type=='4'}" @click="selectSearch('4')">无物资内容：
            <span>{{tableData.equipment||'0'}}</span>人
          </span>
        </el-col>
        <el-col :span="6" type="felx" style="text-align: right">
          <el-button type="primary" plain @click="addShoper(1)" size="small">新建骑手</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData.list" stripe style="width: 100%" >
         <el-table-column type="expand" width="30" align="left">
          <template slot-scope="props">
            <el-row class="shop-msg">
              <el-col :span="8">
                <div class="head">骑手信息</div>
                <ul class="item">
                  <li><span class="title">姓名：</span><span class="content">{{props.row.name}}</span></li>
                  <li><span class="title">手机号：</span><span>{{props.row.munber}}</span></li>
                  <li><span class="title">身份证：</span><span>{{props.row.idnumber}}</span></li>
                  <li v-if="props.row.bankaccount"><span class="title">银行卡：</span><span class="content">{{props.row.bankaccount}}</span></li>
                  <li v-if="props.row.bankaccount"><span class="title">开户行：</span><span class="content">{{props.row.bankname}}</span></li>
                  <li v-if="props.row.bankaccount"><span class="title">支行信息：</span><span class="content">{{props.row.branchinformation}}</span></li>
                  <li v-if="!props.row.bankaccount"><span class="title">银行卡：</span><span class="content">未绑定</span></li>
                </ul>
              </el-col>
              <el-col :span="8">
                <div class="head">工作信息</div>
                <ul class="item">
                  <li><span class="title">入职时间：</span><span class="content">{{props.row.createtime}}</span></li>
                  <li><span class="title">工作性质：</span><span class="content">{{props.row.working === 1 ? '全职' : '兼职'}}</span></li>
                  <li><span class="title">骑手等级：</span><span>{{props.row.creditratingname}}</span></li>
                  <li><span class="title">配送物质：</span><span class="content">{{props.row.equipment || '未分配'}}</span></li>
                  <li><span class="title">最大配送：</span><span class="content">{{filtersKmToOtherUnit(props.row.distributionmun)}}{{comConfig.lengthUnit}}</span></li>
                  <li><span class="title">跑腿抽成：</span><span class="content">{{props.row.coefficient || 0}} %</span></li>
                </ul>
              </el-col>
              <el-col :span="8">
                <div class="head">骑手证件</div>
                <ul class="item">
                  <li class="flex"><span class="title">身份证：</span>
                    <span class="img-wrap" v-if="props.row.idcardpositiveload">
                       <pt-upload class="update-list" v-for="item in props.row.idcardpositiveload.split(',')" :key="item" :disabled="true" :upLoadImg="item" />
                    </span>
                    <span class="content" v-else>未添加</span>
                  </li>
                  <li class="flex"><span class="title">其他证件：</span>
                    <span class="img-wrap" v-if="props.row.otherfileload">
                      <pt-upload class="update-list" v-for="item in props.row.otherfileload.split(',')" :key="item" :disabled="true" :upLoadImg="item" />
                    </span>
                    <span class="content" v-else>未添加</span>
                  </li>
                </ul>
              </el-col>
            </el-row>
            <el-form label-position="left" v-if="props.row.bankaccount" inline class="demo-table-expand">
              <el-form-item label="工作状态">{{props.row.working === 1 ? '全职' : '兼职'}}</el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="60" align="left" />
        <el-table-column prop="createtime" label="入职时间" min-width="140" align="left" />
        <el-table-column prop="name" label="骑手" min-width="100" align="left" />
        <el-table-column prop="munber" label="手机号" min-width="100" align="left" />
        <el-table-column label="工作性质" min-width="80" align="left">
          <template slot-scope="scope">{{scope.row.workType===1?'全职':'兼职'}}</template>
        </el-table-column>
        <!-- <el-table-column prop="equipment" label="物资内容" min-width="160" align="left" /> -->
        <el-table-column prop="creditratingname" label="骑手等级" min-width="80" align="left" />
        <el-table-column label="最大配送" min-width="80" align="left" >
          <template slot-scope="scope">{{scope.row.distributionmun || 0}} {{comConfig.length}} </template>
        </el-table-column>
        <el-table-column prop="coefficient" label="跑腿抽成" min-width="80" align="left">
          <template slot-scope="scope"> {{scope.row.coefficient || 0}} % </template>
        </el-table-column>
        <el-table-column label="工作状态" min-width="80" align="left">
          <template slot-scope="scope">{{scope.row.working=='1'?'上班':scope.row.working=='0'?'下班':'未知' }} </template>
        </el-table-column>
        <el-table-column prop="status" label="停/启用" min-width="100" align="left">
          <template slot-scope="scope"><span>{{scope.row.status=='-1'?'已停用':'已启用'}}</span></template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220" align="right">
          <template slot-scope="scope">
            <el-button v-if='scope.row.status=="-1"' type="success" size="mini" style="padding: 2px;" @click="stop(scope.row, 1)">启用</el-button>
            <el-button v-else type="danger" size="mini" style="padding: 2px;" @click="stop(scope.row, 2)">停用</el-button>
            <el-button class="el-text-check" type="text" size="mini" @click="addShoper(2,scope.row)" >编辑</el-button>
            <el-button class="el-text-danger" type="text" size="mini" @click="remove(scope.row.id)">删除</el-button>
            <el-button class="el-text-success" type="text" size="mini" v-if="scope.row.working == '0' && scope.row.status == '0'" @click="remind(scope.row.id)">提醒开工</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pt-table-loading v-show="isloadingTable" />
      <pt-pagination ref="pagination" :total="tableData.count" @listeningEvent="triggerEvent" />
    </div>
    <el-dialog :title="(edit ? '修改': '新增')+'骑手'" v-dialogDrag :visible.sync="dialogTableVisible" width="700px" :close-on-press-escap="true">
      <el-form :model="form" ref="ruleForm" label-width="100px"  size="small">
        <el-form-item label="所属区域" prop="agentid" :rules="[{ required: true, message: '请在列表页面上选择区域', trigger: 'change' }]">
          <el-row type="flex">
            <el-select v-model="form.agentid" @change="changeAgentId">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-row>
        </el-form-item>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请输入骑手姓名', trigger: 'blur' }]">
              <el-input v-model="form.name" placeholder="请输入骑手姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="munber" :rules="[{ required: true, message: '请输入骑手手机号', trigger: 'blur' }]">
              <el-input v-model="form.munber" type="number" placeholder="请输入骑手手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="身份证号" prop="idnumber" :rules="[{ required: true, message: '请输入骑手身份证', trigger: 'blur' }]">
          <el-input v-model="form.idnumber" placeholder="请输入骑手身份证" />
        </el-form-item>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="跑腿抽成" prop="coefficient" :rules="[{required: true, message: '折扣比例未填'}]">
              <el-input-number v-model="form.coefficient" :min='0' :max='100' :precision='0' />&nbsp;%
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大配送量" prop="distributionmun" :rules="[{required: true, message: '最大配送费未填'}]">
              <el-input-number v-model="form.distributionmun" :min='0' :max='100' :precision='0' />&nbsp;单
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="工作性质" prop="workType" :rules="[{ required: true, message: '请选择工作性质', trigger: 'change' }]">
              <el-select v-model="form.workType"  placeholder="请选择" size="small">
                <el-option label="全职" :value="1" />
                <el-option label="兼职" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="骑手等级" prop="creditlevelid" :rules="[{ required: true, message: '请选择骑手等级', trigger: 'change' }]">
              <el-select v-model="form.creditlevelid"  placeholder="请选择" size="small">
                <el-option v-for="item in lvlupList" :key="item.sortname" :label="item.sortname" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="配送物资内容" prop="equipment">
          <el-input v-model="form.equipment" placeholder="请输入配送物资内容(选填)" />
        </el-form-item>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="密码" prop="pass">
              <el-input v-model="form.pass" placeholder="请输入密码，默认123456" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="checkPass">
              <el-input v-model="form.checkPass" placeholder="请输入再次输入密码" />
            </el-form-item>
          </el-col>
        </el-row>
         <el-form-item label="银行卡">
          <el-input v-model="form.bankaccount" placeholder="请输入骑手银行卡(选填)" />
        </el-form-item>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="开户行" prop="bankname" :rules="[{ required: form.bankaccount ? true : false, message: '已填写银行卡，需填开户行', trigger: 'change' }]">
              <el-input v-model="form.bankname" placeholder="请输入骑手开户行" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支行信息" prop="branchinformation"
              :rules="[{ required: form.bankaccount ? true : false, message: '已填写银行卡，需填支行信息', trigger: 'change' }]">
              <el-input v-model="form.branchinformation" placeholder="请输入开户行支行信息" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="身份证正反面" prop="idnumberImgs" :rules="[{validator: validatorImg }]">
          <pt-uploads :size="5" :limit="2" :upLoadImg="form.idnumberImg" @getUploadList="getUpLoad1" @deleteImage="deleteInnerImg1" />
        </el-form-item>
        <el-form-item label="其他证件" style="max-width: 600px;">
          <pt-uploads :size="5" :limit="5" :upLoadImg="form.ohterImg" @getUploadList="getUpLoad2" @deleteImage="deleteInnerImg2" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import imd5 from '@/utils/md5.js'
  import { kmToOtherUnit } from '@/utils/unitChange.js'
  export default {
    data() {
      var validatePass1 = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else {
          if (this.form.checkPass !== "") {
            this.$refs.ruleForm.validateField("newPassword2");
          }
          callback();
        }
      }
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.form.pass) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback()
        }
      };
      return {
        lvlupList: [], // 骑手等级信息
        addOrEdit: '添加',  //添加 修改文本提示
        isloadingSave: false,  //保存或修改
        isloadingTable: false,  //表单等待
        dialogTableVisible: false,  //骑手
        form: { //新增或修改角色
          agentid: '', // 区域d
          creditlevelid: null, // 等级id
          creditRatingName: '', //  等级名
          creditRating: 0, // ？？？？
          name: '', // 骑手姓名
          munber: '', // 手机号
          equipment:'', // 配送物质
          distributionmun: '', // 最大配送数量
          idnumber: '', // 身份证号
          coefficient: '',
          workType: null, // 工资性质
          pass: '',   //输入密码
          checkPass: '', //确认密码
          bankaccount: '', // 骑手银行卡号
          bankname: '', // 开户行名称
          branchinformation: '', // 支行信息
          idnumberImg: [],
          idnumberImgs: [], // 临时字段
          ohterImg: [],
          ohterImgs: [] // 临时字段
        },
        edit: '',
        params: { //表格查询
          page: 0,
          pagesize: 10,
          name: '',
          workType: null,
          status: null,
          type: '0'
        },
        tableData: {} //表单数据
      }
    },
    computed: {
      restaurants() { // 区域据
        return this.$store.state.agentList
      }
    },
    watch: { // 监听时间变化
      restaurants: {
        handler(val, oldVal) {
          if (val && val.length) {
            this.form.agentid = val[0].id
            this.getLvlupMsg()
          }
        },
        deep: true
      }
    },
    methods: {
      filtersKmToOtherUnit(num) { // 单位换算
        return kmToOtherUnit(num)
      },
      validatorImg(rule, value, callback){
        if (value.length && value.length !== 2) {
          callback(new Error("请上传身份证的正反面两张图片"))
        } else {
          callback()
        }
      },
      getUpLoad1(imgs) { // 本地添加店内图片
        this.form.idnumberImgs.push({name: imgs.name, url: `http://image.jiaowawang.cn/${imgs.url}`})
      },
       getUpLoad2(imgs) { // 本地添加店内图片
        this.form.ohterImgs.push({name: imgs.name, url: `http://image.jiaowawang.cn/${imgs.url}`})
      },
      deleteInnerImg1(img) { // 本地删除店内图片
        const index = this.form.idnumberImgs.findIndex(item => {
          return `http://image.jiaowawang.cn/${img}` === `${item.url}`
        })
        if (index > -1) this.form.idnumberImgs.splice(index, 1)
      },
      deleteInnerImg2(img) { // 本地删除店内图片
        const index = this.form.ohterImgs.findIndex(item => {
          return `http://image.jiaowawang.cn/${img}` === `${item.url}`
        })
        if (index > -1) this.form.ohterImgs.splice(index, 1)
      },
      addShoper(type, row) {  //打开对话框，棋手
        const agentid = this.form.agentid
        if (type == 1) {
          if (this.lvlupList.length === 0) {
            this.$message.error('请先添加骑手荣誉等级')
            return false
          }
          this.dialogTableVisible = true
          this.$nextTick(() => {
            this.$refs['ruleForm'].resetFields()
            this.edit = ''
            this.form = {
              agentid, // 区域d
              creditlevelid: null, // 等级id
              creditRatingName: '', //  等级名
              creditRating: 0, // ？？？？
              name: '', // 骑手姓名
              munber: '', // 手机号
              equipment:'', // 配送物质
              distributionmun: '', // 最大配送数量
              idnumber: '', // 身份证号
              coefficient: '',
              workType: null, // 工资性质
              pass: '',   //输入密码
              checkPass: '', //确认密码
              idnumberImg: [],
              idnumberImgs: [], // 临时字段
              ohterImg: [],
              ohterImgs: [] // 临时字段
            }
          })
        } else if (type == 2) {
          this.edit = row.id
          this.dialogTableVisible = true
          this.$nextTick(() => {
            this.$refs['ruleForm'].resetFields()
            for (const key in this.form) {
              if (key === 'agentid') {
                this.form.agentid = agentid
              } else if (key === 'creditRating') {
                this.form.creditRating = 0
              } else if (key === 'workType') {
                this.form.workType = row.workType || 0
              } else if (key === 'pass' || key === 'checkPass') {
                this.form[key] = ''
              } else if (key === 'idnumberImg' || key === 'idnumberImgs') {
                if (row.idcardpositiveload && row.idcardpositiveload.split(',').length) {
                   this.form[key] = row.idcardpositiveload.split(',').map((item, index) => {
                    return {name: `已保存的图片${index + 1}.jpg`, url: `http://image.jiaowawang.cn/${item}`}
                  })
                } else {
                  this.form[key] = []
                }
              } else if (key === 'ohterImg' || key === 'ohterImgs') {
               if (row.otherfileload && row.otherfileload.split(',').length) {
                   this.form[key] = row.otherfileload.split(',').map((item, index) => {
                    return {name: `已保存的图片${index + 1}.jpg`, url: `http://image.jiaowawang.cn/${item}`}
                  })
                } else {
                  this.form[key] = []
                }
              } else {
                this.form[key] = row[key]
              }
            }
          })
        }
      },
      triggerEvent(type,val) { // 分页器
        if (type === 'page') {
          this.params.page = val - 1
        } else if (type === 'size') {
          this.params.page = 0
          this.params.pageSize = val
        }
        this.getTableList()
      },
      inquiry() { // 查询
        this.getLvlupMsg(() => {
          this.$refs.pagination.handleSizeChange(10)
        })
      },
      getTableList() { //获取骑手数据
        this.isloadingTable = true
        const params = { ...this.params }
        params.agentid = this.form.agentid
        this.$http.get('/server/shopper/findmax?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.tableData = res.data.data
          }
        }).finally(() => { this.isloadingTable = false })
      },
      getLvlupMsg(callback) { //获取骑手等级数据
        this.isloadingTable = true
        this.$http.get('/server/shopperCreditLevel/select?agentId=' + this.form.agentid).then(res => {
          if (res.data.success) {
            this.lvlupList = res.data.data
            if (callback) {
              callback()
            } else {
              this.getTableList()
            }
          }
        }).finally(() => { this.isloadingTable = false })
      },
      submitForm(ruleForm) {
        this.$refs[ruleForm].validate((valid) => {
          if (valid) {
            const params = { ...this.form }
            const index = this.lvlupList.findIndex(item => {
              return params.creditlevelid == item.id
            })
            if (index === -1){
              this.$message.error('无法获取骑手等级名称')
              return false
            }
            params.creditRatingName = this.lvlupList[index].sortname
            params.username = params.munber
            params.otherfileload = params.ohterImgs.length ? params.ohterImgs.map(i => i.url.replace('http://image.jiaowawang.cn/', '')).join(',') : ''
            params.idcardpositiveload = params.idnumberImgs.length ? params.idnumberImgs.map(i => i.url.replace('http://image.jiaowawang.cn/', '')).join(',') : ''
            delete params.idnumberImg
            delete params.idnumberImgs
            delete params.ohterImg
            delete params.ohterImgs
            params.password = params.checkPass ? imd5.md5(params.checkPass) :
              (params.password ? params.password :'E10ADC3949BA59ABBE56E057F20F883E') // 其实就是123456
            if (this.edit) {
              params.id = this.edit
              this.$http.post('/server/shopper/update1', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message.success('修改成功！')
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              })
            } else {
              this.$http.post('/server/shopper/add', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message.success('创建成功！')
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              })
            }
          }
        })
      },
      stop(row, type) { // 停用骑手
        const status = {
          status: row.status == '-1' ? '0' : '-1',
          id: row.id
        }
        if (type === 2) status.working = 0
        this.$http.post('/server/shopper//change', JSON.stringify(status)).then(res => {
          if (res.data.success) {
            this.$message.success('修改成功！')
            this.getTableList()
          }
        })
      },
      remove(id) {   //删除骑手
        let rem = { id }
        this.$http.post('/server/shopper/delete1', JSON.stringify(rem)).then(res => {
          if (res.data.success) {
            this.$message.success('删除成功！')
            this.getTableList()
          }
        })
      },
      remind(id) { //提醒骑手开天
        const rem = {id}
        this.$http.post('/server/shopper/beginwork', JSON.stringify(rem)).then(res => {
          if (res.data.success) {
            this.$message.success('成功提醒骑手！')
            this.getTableList()
          }
        })
      },
      selectSearch(type) { //切换状态
        this.params.type = type
        this.$refs.pagination.handleSizeChange(10)
      },
      changeAgentId() { // 骑手变更区域
        this.form.creditlevelid = null
        this.lvlupList = []
        this.getLvlupMsg()
      }
    },
    mounted() {
      if (this.restaurants && this.restaurants.length) {
        this.form.agentid = this.restaurants[0].id
        this.getLvlupMsg()
      }
    }
  }
</script>

<style lang="scss" scoped>
 @import './css/info.scss';
</style>
